/*
 * 3 threads
 *  plane_height_detect
 *  plane_height_watchdog
 *  wait_child_to_die
 */
#include<pthread.h>
#include<unistd.h>
#include<wait.h>
#include<stdio.h>
#include<signal.h>

#include"monitor.h"
#include"start.h"

#include<gpiox.h>
#include<us100.h>
#include<global_header.h>
#include<wflyctrl.h>

#define MONITOR "Monitor: "

#define MONITOR_THREADS_NUM 2
pthread_t monitor_tid_ary[MONITOR_THREADS_NUM];

// #define US100_HEALTH_VALUE 5
//int us100_health; /* keep us100_health = 5, means it's health */

#if 0
void *plane_height_detect(void *ary) {
    /* us100-trig-pin */
#define INIT_PIN_GROUP  GPIOD
#define INIT_PIN_NUM    17

    /* us100-echo-pin */
#define BACK_PIN_GROUP  GPIOD
#define BACK_PIN_NUM    21
    while(1) {
        us100(INIT_PIN_GROUP, INIT_PIN_NUM,
                BACK_PIN_GROUP, BACK_PIN_NUM,
                (void *)plane_height);
        us100_health = US100_HEALTH_VALUE; /* us100_health_value */
        // printf("\e[44;37;1m""-""\e[0m");
        abs_usleep(500);
        /* just a thread-atomic-operate,
         * so that it can more friendly cancel-able. */
    }
}
#endif

static void plane_emergency_land(void) {
#if 0
    if(*plane_height > 20) {
        printf("\t\e[47;34;1m"
                "Begin to emergence land."
                "\e[0m\n");
        //test_plane_land_func();
    } else {
        printf("\t\e[47;34;1m"
                "%s: the plane is already land."
                "\e[0m\n",
                __func__);
    }
#endif
    test_plane_land_func();
    plane_already_land_flag = 1;
}

void wait_child_to_die(int signum) {
    int ret;
    ret = waitpid(mainctrl_pid, NULL, WNOHANG);
    if(ret == mainctrl_pid) {
        printf("\t\e[43;31;1m"
                MONITOR
                "mainctrl is dead."
                "\e[0m\n");
        plane_emergency_land();
    }
}
